package com.oocl.dao.impl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import javax.annotation.Resource;
import javax.sql.DataSource;

import org.springframework.stereotype.Repository;

import com.oocl.dao.UserDao;
import com.oocl.pojo.User;
import com.oocl.util.DBUtil;

@Repository("userDao")
public class UserDaoImpl implements UserDao{
	@Resource(name="dataSource")
	private DataSource dataSource;
	
	@Override
	public User addUser(User user) {
		if(null==user){
			return null;
		}
		Connection connection = null;
		PreparedStatement ps = null;
		String sql = "insert into users(id,username,password,age) values(?,?,?,?)";
		int m=0;
		try {
			connection = dataSource.getConnection();
			ps = connection.prepareStatement(sql);
			ps.setString(1, user.getId());
			ps.setString(2, user.getUsername());
			ps.setString(3, user.getPassword());
			ps.setInt(4, user.getAge());
			m=ps.executeUpdate();
			if(m>0){
				return user;
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}finally {
			DBUtil.release(null, ps, connection);
		}
		return null;
	}

	@Override
	public User findUserByUsername(String username) {
		Connection connection = null;
		PreparedStatement ps = null;
		ResultSet rs = null;
		User user = null;
		String sql = "select * from users where username=?";
		try {
			connection = dataSource.getConnection();
			ps = connection.prepareStatement(sql);
			ps.setString(1, username);
			rs = ps.executeQuery();
			while(rs.next()){
				user = new User();
				user.setId(rs.getString(1));
				user.setUsername(rs.getString(2));
				user.setPassword(rs.getString(3));
				user.setAge(rs.getInt(4));
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}finally {
			DBUtil.release(rs, ps, connection);
		}
		return user;
	}

}
